package com.sinosoft.ptas.control;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.sinosoft.framework.core.api.domain.OrganizationEntity;
import com.sinosoft.framework.core.api.domain.PmsData;
import com.sinosoft.framework.core.api.service.OrganizationService;
import com.sinosoft.framework.core.common.exception.BusinessException;
import com.sinosoft.framework.core.common.utils.StringUtil;
import com.sinosoft.framework.core.common.utils.ajax.ResponseData;
import com.sinosoft.ptas.control.dto.NoticeData;
import com.sinosoft.ptas.control.dto.OrganizationNoticeRefData;
import com.sinosoft.ptas.entity.NoticeEntity;
import com.sinosoft.ptas.entity.OrganizationNoticeRefEntity;
import com.sinosoft.ptas.entity.ReportEntity;
import com.sinosoft.ptas.service.NoticeService;
import com.sinosoft.ptas.system.commom.CommonConstant;
import com.sinosoft.ptas.system.commom.ExceptionConstant;
import com.sinosoft.ptas.system.commom.PtasConstant;
import com.sinosoft.ptas.system.security.SecurityUtil;
import com.sinosoft.ptas.system.util.FileUploadingUtil;

/**
 * 公告的控制层
 * @author zhangxiaolong
 *
 */
@Controller
@RequestMapping(value="notice")
public class NoticeController {
	
	@Autowired
	NoticeService noticeService;
	
	@Autowired
	OrganizationService organizationService;

	/**
	 * 添加公告
	 * 先创建公告，再创建公告与司局的对应关系
	 * @param noticeData
	 * @return noticeData
	 */
	@ResponseBody
	@RequestMapping(value="/createNotice.service",method=RequestMethod.POST)
	@Transactional(rollbackFor=Exception.class)
	public ResponseData createNotice(NoticeData noticeData){
		String id=UUID.randomUUID().toString();
		noticeData.setId(id);
		noticeData.setPublishTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));//时间类型格式化
		noticeService.createNotice(noticeData.toEntity());
		OrganizationNoticeRefEntity organizationNoticeRefEntity=new OrganizationNoticeRefEntity();//用来接收切面时间
		String noticeId=id;
		String[] indentify =noticeData.getNoticeObject();//获取标识
		/*根据标识符获取司局信息*/
		List<OrganizationEntity> organizationEntitys=organizationService.retrieveOrganizationsByIdentifys(indentify);
		int size=organizationEntitys.size();
		/*数组赋值司局的编号*/
		String[] orgIds=new String[size];
		for(int i=0;i<size;i++){
			orgIds[i]=organizationEntitys.get(i).getId();
		}
		/*创建司局和公告的对应关系*/
		noticeService.createOrgNoticeRef(organizationNoticeRefEntity, noticeId, orgIds);
		return new ResponseData(true,noticeData);
	}
	

	/**
	 * 根据公告编号删除公告
	 * 先删除公告和司局的对应关系，再删除公告
	 * @param id
	 */
	@ResponseBody
	@RequestMapping(value="/deleteNoticeByid.service",method=RequestMethod.POST)
	public ResponseData deleteNoticeByid(String id){
		noticeService.deleteNoticeByid(id);
		return new ResponseData(true,CommonConstant.DELETE_SUCCESS);
	}

	/**
	 * 更新公告
	 * @param noticeEntity
	 *//*
	@ResponseBody
	@RequestMapping(value="/updateNotice.service",method=RequestMethod.POST)
	public ResponseData updateNotice(NoticeData noticeData){
		NoticeEntity noticeEntity=noticeData.toEntity();
		noticeService.updateNotice(noticeEntity);
		return new ResponseData(true,noticeData);
	}*/
	
	/**
	 * 根据公告编号查询公告
	 * @param id
	 * @return 公告实体
	 */
	@ResponseBody
	@RequestMapping(value="/retieveNoticeByid.service",method=RequestMethod.POST)
	public ResponseData retieveNoticeByid(String id){
		NoticeEntity noticeEntity=noticeService.retieveNoticeByid(id);
		return new ResponseData(true,toNoticeData(noticeEntity));
	}

	/**
	 * 查询全部公告并降序排序
	 * @return 公告传输类集合
	 */
	@ResponseBody
	@RequestMapping(value="/retieveNotices.service",method=RequestMethod.POST)
	public ResponseData retieveNotices(){
		List<NoticeEntity> noticeEntitys=new ArrayList<NoticeEntity>();
		NoticeEntity noticeEntity=new NoticeEntity();
		noticeEntitys=noticeService.retiveNotices(noticeEntity);
		return new ResponseData(true,toNoticeDatas(noticeEntitys));
	}

	/**
	 * 查询全部公告和司局的对应关系
	 * @return 公告和司局的对应关系传输类集合
	 */
	@ResponseBody
	@RequestMapping(value="/retrieveOrgNoticeRefs.service",method=RequestMethod.POST)
	public ResponseData retrieveOrgNoticeRefs(){
		List<OrganizationNoticeRefEntity> OrgNoticeRefs=noticeService.retrieveOrgNoticeRefs();
		List<OrganizationNoticeRefData> organizationNoticeRefDatas=toOrganizationNoticeRefDatas(OrgNoticeRefs);
		return new ResponseData(true,organizationNoticeRefDatas);
	}
	
	/**
	 * 省局查询公告
	 * @return 公告集合
	 */
	@ResponseBody
	@RequestMapping(value="/retiveNoticesByOrgId.service",method=RequestMethod.POST)
	public ResponseData retiveNoticesByOrgId(){
		PmsData pmsData = (PmsData)SecurityUtil.getSessionValue(PtasConstant.pms_app_content);
		String orgId=pmsData.getOid();
		List<NoticeEntity> noticeEntitys=noticeService.retiveNoticesByOrgId(orgId);
		return new ResponseData(true,toNoticeDatas(noticeEntitys));
	}
	
	/**
	 * 查询未读公告条数
	 * @return 公告集合
	 */
	@ResponseBody
	@RequestMapping(value="/retrieveNoReadNoticeByOrgId.service",method=RequestMethod.POST)
	public ResponseData retrieveNoReadNoticeByOrgId(){
		PmsData pmsData = (PmsData)SecurityUtil.getSessionValue(PtasConstant.pms_app_content);
		String orgId=pmsData.getOid();
		int number=noticeService.retrieveNoReadNoticeByOrgId(orgId);
		return new ResponseData(true,number);
	}

	/**
	 * 更新公告点击量 和状态
	 * 一个司局点击一次   计算为一个
	 * @param noticeId
	 * @throws BusinessException
	 */
	@ResponseBody
	@RequestMapping(value="/updateNoticeClickNumAndState.service",method=RequestMethod.POST)
	public ResponseData updateNoticeClickNumAndState(String noticeId,String code){
		if(StringUtil.isBlank(noticeId)||StringUtil.isBlank(code)){
			return new ResponseData(false,ExceptionConstant.ID_NULL_CODE,ExceptionConstant.ID_NULL_MESSAGE,null);
		}
		noticeService.updateNoticeClickNumAndState(noticeId, code);
		return null;
	}
	
	 /**
     * 上传文件
     * @param request
     * @param noticeId
     * @return
     */
    @RequestMapping(value = "/upload.service", method = RequestMethod.POST)
    @ResponseBody
    @Transactional(rollbackFor=Exception.class)
    public ResponseData doUpload(HttpServletRequest request,String noticeId) {
    	String filePath="";
        iniFileDir(request);  
        NoticeEntity notice=noticeService.retieveNoticeByid(noticeId);
        if(notice==null){
        	 return new ResponseData(false,null,"数据库中没有这条公告信息",null);
        }
        try {  
            MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;  
            Map<String, String> uploadedFiles = FileUploadingUtil.upload(mRequest.getFileMap());  
  
            Iterator<Entry<String, String>> iter = uploadedFiles.entrySet().iterator();  
            while (iter.hasNext()) {
                Entry<String, String> each = iter.next();  
                System.out.print("Uploaded File Name = " + each.getKey());  
                System.out.println(", Saved Path in Server = " + each.getValue()); 
                filePath=each.getValue();
            }
            notice.setAttachmentUrl(filePath);
            noticeService.updateNotice(notice);
            return new ResponseData(true,filePath);
        } catch (Exception e) {  
            e.printStackTrace();  
            return new ResponseData(false,null,e.getMessage(),null);
        }  
    }  
	
	/**
	 * @return 实体类转化为传输类
	 */
	private NoticeData toNoticeData(NoticeEntity noticeEntity) {
		NoticeData noticeData = new NoticeData();
		noticeData.toNoticeData(noticeEntity);
		return noticeData;
	}
	
	/**
	 * @return 实体类集合转化为传输类集合
	 */
	private List<NoticeData> toNoticeDatas(List<NoticeEntity> noticeEntitys) {
		int size = noticeEntitys.size();
		List<NoticeData> noticeDatas = new ArrayList<NoticeData>();
		for (int i = 0; i < size; i++) { // 循环将实体数据转换为传输数据
			NoticeData noticeData = new NoticeData();
			noticeData.toNoticeData(noticeEntitys.get(i));
			noticeDatas.add(noticeData);
		}
		return noticeDatas;
	}
	
	/**
	 * 公告与司局对应关系实体类集合转化为传输类集合
	 * @return 
	 */
	private List<OrganizationNoticeRefData> toOrganizationNoticeRefDatas(List<OrganizationNoticeRefEntity> organizationNoticeRefEntitys) {
		int size = organizationNoticeRefEntitys.size();
		List<OrganizationNoticeRefData> organizationNoticeRefDatas = new ArrayList<OrganizationNoticeRefData>();
		for (int i = 0; i < size; i++) { // 循环将实体数据转换为传输数据
			OrganizationNoticeRefData organizationNoticeRefData = new OrganizationNoticeRefData();
			organizationNoticeRefData.toData(organizationNoticeRefEntitys.get(i));
			organizationNoticeRefDatas.add(organizationNoticeRefData);
		}
		return organizationNoticeRefDatas;
	}
	
		/**
	    * 初始化文件的保存路径
	    */
	    private String iniFileDir(HttpServletRequest request) { 
	    	PmsData pmsData = (PmsData)SecurityUtil.getSessionValue(PtasConstant.pms_app_content);
	        FileUploadingUtil.FILEDIR = request.getSession().getServletContext().getRealPath("/") +"resources//book//"+ pmsData.getOname()+"123";
	        if (FileUploadingUtil.FILEDIR == null) {  
	            FileUploadingUtil.FILEDIR = request.getSession().getServletContext().getRealPath("/")+"resources//book//"+pmsData.getOname()+"123"; 
	        }  
	        return FileUploadingUtil.FILEDIR;
	    }
		
}
